package com.ztools.pc.async;

import com.ztools.common.model.pc.coupon.CouponTemplate;
import com.ztools.common.model.pc.coupon.CouponUsed;
import com.ztools.common.util.common.RedisHelper;
import com.ztools.common.util.common.enumUnit.CouponUsedRouteEnum;
import com.ztools.pc.service.coupon.CouponTemplateService;
import com.ztools.pc.service.coupon.CouponUsedService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;

import static com.ztools.common.util.pc.RedisUtil.CACHE_COUPON_PACKET;

/**
 * @Author: seeTools
 * @Date: 2023/6/8  9:31
 * @Version 1.0
 * 优惠券异步任务
 */
@Async
@Component
public class CouponAsync {

    @Resource
    private CouponUsedService couponUsedService;
    @Resource
    private CouponTemplateService couponTemplateService;
    @Resource
    private RedisHelper redisHelper;


    /**
     * 使用优惠券
     *
     * @param memberId            会员ID
     * @param couponUsedRouteEnum 使用途径
     * @param templateIds         优惠券模板IDS
     */
    public void useCoupons(Long memberId, CouponUsedRouteEnum couponUsedRouteEnum, String templateIds) {
        Date date = new Date();
        ArrayList<CouponUsed> couponUsedList = new ArrayList<>();
        // 生成已用券数据
        for (String template : templateIds.split(",")) {
            CouponTemplate coupon = couponTemplateService.getById(Long.parseLong(template));
            CouponUsed couponUsed = CouponUsed.builder()
                    .templateId(coupon.getId())
                    .couponType(coupon.getType())
                    .memberId(memberId)
                    .startDate(date)
                    .endDate(date)
                    .useTime(date)
                    .useRoute(couponUsedRouteEnum.getRoute())
                    .remark(couponUsedRouteEnum.getName())
                    .build();
            couponUsedList.add(couponUsed);
        }
        // 增加已用券数据
        couponUsedService.saveBatch(couponUsedList);
    }


    /**
     * 刷新指定会员券包
     *
     * @param memberId memberId
     */
    public void refreshPacket(Long memberId) {
        String key = CACHE_COUPON_PACKET + memberId + ":";
        redisHelper.scan(key + "*", item -> {
            String redisKey = new String(item, StandardCharsets.UTF_8);
            redisHelper.delete(redisKey);
        });
    }


    /**
     * 刷新所有会员券包
     */
    public void refreshAllPacket() {
        String key = CACHE_COUPON_PACKET + "*";
        redisHelper.scan(key + "*", item -> {
            String redisKey = new String(item, StandardCharsets.UTF_8);
            redisHelper.delete(redisKey);
        });
    }

}
